﻿using System;
using System.Configuration;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

namespace mojoPortal.Web.RS.SBM.Controls
{
    public partial class ModalManageAppointmentControl : RSBaseUserControl
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void btnEditAppointment_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                btnSaveAppointment.Visible = true;
                btnDeleteAppointment.Visible = true;
                btnEditAppointment.Visible = false;

                
                RSSBMCommonFunctions.SetControlsEnabledState(UpdatePanelManageAppointment.ContentTemplateContainer, true);
            }
        }
        protected void btnSaveAppointment_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                int CompanyId = userIdentity.RSCompanyId;

                int LocationId = hfLocationId.Value == "" ? 0 : Convert.ToInt32(hfLocationId.Value); // ucLocationHeaderControl.LocationId;
                int AppointmentId = txtAppointmentId.Text == "" ? 0 : Convert.ToInt32(txtAppointmentId.Text);

                string Subject = txtSubject.Text.Trim();
                string StartDT = txtStartDate.Text + " " + txtStartTime.Text.Trim();
                string EndDT = txtEndDate.Text + " " + txtEndTime.Text.Trim();
                string Location = RSSBMCommonFunctions.GetLocationFullAddressByID(CompanyId, LocationId);
                string Description = txtDescription.Text.Trim();
                string Response = txtResponse.Text.Trim();
                string AssignTo = RSSBMCommonFunctions.GetMultiSelectValue(chkAssignTo); //ddlAssignTo.SelectedValue);
                int AppointmentTypeID = Convert.ToInt32(ddlAppointmentType.SelectedValue);
                //int Status = Convert.ToInt32(txtStatus.Text);

                SqlCommand sqlCmd = new SqlCommand();

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Subject", SqlDbType.NVarChar, 250, ParameterDirection.Input, Subject);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Description", SqlDbType.NVarChar, -1, ParameterDirection.Input, Description);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Response", SqlDbType.NVarChar, -1, ParameterDirection.Input, Response);

                if (StartDT.Trim().Length > 0)
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@StartDT", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(StartDT));
                if (EndDT.Trim().Length > 0)
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@EndDT", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(EndDT));

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Location", SqlDbType.NVarChar, 250, ParameterDirection.Input, Location);

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@AssignTo", SqlDbType.NVarChar, 100, ParameterDirection.Input, AssignTo);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@AppointmentTypeID", SqlDbType.Int, 0, ParameterDirection.Input, AppointmentTypeID);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@LocationId", SqlDbType.Int, 0, ParameterDirection.Input, LocationId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@AppointmentId", SqlDbType.Int, 0, ParameterDirection.Input, AppointmentId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
                SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveAppointment");
                SQLHelper.ExecuteScalarCmd(sqlCmd);

                int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                lblMessage.Text = "Appointment Successfully Saved!";
                lblMessage.ForeColor = System.Drawing.Color.DarkBlue;
                hfRedirectURL.Value = Request.RawUrl;
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";
                lblMessage.ForeColor = System.Drawing.Color.DarkRed;
            }
            btnEditAppointment.Visible = false;
            btnSaveAppointment.Visible = false;
            btnDeleteAppointment.Visible = false;
            RSSBMCommonFunctions.SetControlsEnabledState(UpdatePanelManageAppointment.ContentTemplateContainer, false);

        }

        protected void btnDeleteAppointment_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite && userIdentity.RSCanDelete)
            {
                int CompanyId = userIdentity.RSCompanyId;

                int LocationId = hfLocationId.Value == "" ? 0 : Convert.ToInt32(hfLocationId.Value); //ucLocationHeaderControl.LocationId;
                int AppointmentId = txtAppointmentId.Text == "" ? 0 : Convert.ToInt32(txtAppointmentId.Text);

                if (CompanyId > 0 && AppointmentId > 0 && LocationId > 0)
                {
                    SqlCommand sqlCmd = new SqlCommand();
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@locationid", SqlDbType.Int, 0, ParameterDirection.Input, LocationId);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@appointmentid", SqlDbType.Int, 0, ParameterDirection.Input, AppointmentId);
                    SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "DELETE FROM rs_tblAppointment WHERE AppointmentId=@appointmentId AND LocationId=@locationid AND  CompanyId=@companyid");
                    SQLHelper.ExecuteScalarCmd(sqlCmd);
                    int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                    lblMessage.Text = "Appointment Deleted Successfully!";
                    lblMessage.ForeColor = System.Drawing.Color.DarkBlue;
                }
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";
                lblMessage.ForeColor = System.Drawing.Color.DarkRed;
            }
            btnEditAppointment.Visible = false;
            btnSaveAppointment.Visible = false;
            btnDeleteAppointment.Visible = false;
            RSSBMCommonFunctions.SetControlsEnabledState(UpdatePanelManageAppointment.ContentTemplateContainer, false);
        }

        protected void btnClearAppointment_Click(object sender, EventArgs e)
        {
            txtAppointmentId.Text = "";
            txtSubject.Text = "";
            txtStartDate.Text = "";
            txtStartTime.Text = "";
            txtEndDate.Text = "";
            txtEndTime.Text = "";
            //txtLocation.Text = "";
            txtDescription.Text = "";
            txtResponse.Text = "";
            ddlAppointmentType.SelectedIndex = 0;
            RSSBMCommonFunctions.ClearMultiSelectList(chkAssignTo);
        }

        public void ShowModal(int companyid, int locationid, int appointmentid)
        {
            hfRedirectURL.Value = "";
            lblMessage.Text = "Appointment";

            if (LoadAppointmentByID(companyid, locationid, appointmentid))
            {
                btnEditAppointment.Visible = true;
                btnSaveAppointment.Visible = false;
                btnDeleteAppointment.Visible = false;
                
                RSSBMCommonFunctions.SetControlsEnabledState(UpdatePanelManageAppointment.ContentTemplateContainer, false);
            }
            else
            {
                btnEditAppointment.Visible = false;
                btnSaveAppointment.Visible = true;
                btnDeleteAppointment.Visible = false;
                lblMessage.Text = "Add New Visit";
                
                RSSBMCommonFunctions.SetControlsEnabledState(UpdatePanelManageAppointment.ContentTemplateContainer, true);
            }
            mpeModalManageAppointment.Show();
        }
        protected void btnModalOK_Click(object sender, EventArgs e)
        {
            mpeModalManageAppointment.Hide();
            var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
            nameValues.Set("tabindex", "2");
            string url = Request.Url.AbsolutePath;
            string updatedQueryString = "?" + nameValues.ToString();
            Response.Redirect(url + updatedQueryString);

        }
        public bool LoadAppointmentByID(int companyid, int locationid, int appointmentid)
        {
            bool HasValue = false;
            if (companyid > 0 && locationid > 0)
            {
                hfLocationId.Value = locationid.ToString();
                RSSBMDataLookupLoader.LoadAssignToCHK(companyid, chkAssignTo);
                RSSBMDataLookupLoader.LoadTypeDDL(companyid, "SCHEDULE_CAT", ddlAppointmentType);

                if (appointmentid > 0)
                {
                    txtAppointmentId.Text = appointmentid.ToString();

                    String strSQL = "select AppointmentID,LocationID,Subject,[Start],[End],Location,Description,Response,AssignTo,AppointmentTypeID,Status from rs_tblAppointment where appointmentid=@appointmentid";
                    SqlCommand myCommand;
                    SqlParameter param;
                    SqlConnection myConnection;
                    myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
                    myCommand = new SqlCommand(strSQL, myConnection);
                    SqlDataReader myDataReader;
                    param = new SqlParameter();
                    param.SqlDbType = SqlDbType.Int;
                    param.ParameterName = "@appointmentid";
                    param.Value = appointmentid;
                    myCommand.Parameters.Add(param);
                    myConnection.Open();
                    myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                    if (myDataReader.HasRows)
                    {
                        myDataReader.Read();
                        txtAppointmentId.Text = myDataReader["AppointmentId"].ToString();
                        txtSubject.Text = myDataReader["Subject"].ToString();

                        if (myDataReader["Start"] != DBNull.Value)
                        {
                            DateTime startdt = Convert.ToDateTime(myDataReader["Start"].ToString());
                            txtStartTime.Text = startdt.ToShortTimeString();
                            txtStartDate.Text = startdt.ToShortDateString();
                        }

                        if (myDataReader["End"] != DBNull.Value)
                        {
                            DateTime enddt = Convert.ToDateTime(myDataReader["End"].ToString());
                            txtEndTime.Text = enddt.ToShortTimeString();
                            txtEndDate.Text = enddt.ToShortDateString();
                        }

                        txtDescription.Text = myDataReader["Description"].ToString();
                        txtResponse.Text = myDataReader["Response"].ToString();
                        RSSBMCommonFunctions.SetMultiSelectList(myDataReader["AssignTo"].ToString(), chkAssignTo);
                        if (myDataReader["AppointmentTypeID"] != DBNull.Value)
                            ddlAppointmentType.SelectedValue = myDataReader["AppointmentTypeID"].ToString();

                        HasValue = true;
                    }

                    myConnection.Close();
                }
            }
            return HasValue;
        }


       
        


    }
}